<template>
  <q-page class="q-pa-md">
    <!-- 操作按钮 -->
    <div class="q-mb-md">
      <q-btn color="primary" icon="add" label="新增菜单" @click="showAddDialog(null)" />
      <q-btn color="grey" icon="refresh" label="刷新" class="q-ml-sm" @click="loadMenuTree" />
    </div>

    <!-- 菜单树表格 -->
    <q-card flat bordered>
      <q-card-section>
        <div class="text-h6">菜单列表</div>
      </q-card-section>
      <q-card-section>
        <q-table
          :rows="flattenMenuData"
          :columns="columns"
          row-key="menuId"
          :loading="loading"
          :pagination="{ rowsPerPage: 0 }"
          :rows-per-page-options="[0]"
          flat
          bordered
          hide-pagination
        >
          <!-- 菜单类型 -->
          <template v-slot:body-cell-menuType="props">
            <q-td :props="props">
              <q-badge :color="menuTypeColors[props.row.menuType]">
                {{ menuTypeOptions.find((o) => o.value === props.row.menuType)?.label }}
              </q-badge>
            </q-td>
          </template>

          <!-- 状态 -->
          <template v-slot:body-cell-status="props">
            <q-td :props="props">
              <q-toggle
                v-model="props.row.status"
                checked-icon="check"
                unchecked-icon="clear"
                :true-value="1"
                :false-value="0"
                color="green"
                @update:model-value="toggleStatus(props.row)"
              />
            </q-td>
          </template>

          <!-- 操作列 -->
          <template v-slot:body-cell-actions="props">
            <q-td :props="props" class="q-gutter-x-sm">
              <q-btn dense color="primary" icon="edit" @click="showEditDialog(props.row)">
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn dense color="positive" icon="add" @click="showAddDialog(props.row)">
                <q-tooltip>添加子菜单</q-tooltip>
              </q-btn>
              <q-btn dense color="negative" icon="delete" @click="confirmDelete(props.row)">
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </q-td>
          </template>
        </q-table>
      </q-card-section>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-dialog v-model="dialogVisible" persistent>
      <q-card style="min-width: 600px">
        <q-card-section>
          <div class="text-h6">{{ isEdit ? '编辑菜单' : '新增菜单' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitForm" class="q-gutter-md">
            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="menuForm.menuType"
                  label="菜单类型"
                  :options="menuTypeOptions"
                  outlined
                  emit-value
                  map-options
                  :rules="[(val) => !!val || '请选择菜单类型']"
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-input v-model="menuForm.parentName" label="上级菜单" outlined readonly>
                  <template v-slot:append>
                    <q-icon name="close" class="cursor-pointer" @click="clearParent" />
                  </template>
                </q-input>
              </div>
            </div>

            <q-input
              v-model="menuForm.menuName"
              label="菜单名称"
              :rules="[(val) => !!val || '菜单名称不能为空']"
              outlined
            />

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input
                  v-model="menuForm.orderNum"
                  label="显示排序"
                  type="number"
                  :rules="[(val) => val >= 0 || '排序必须大于等于0']"
                  outlined
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="menuForm.isFrame"
                  label="是否外链"
                  :options="frameOptions"
                  outlined
                  emit-value
                  map-options
                />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input
                  v-model="menuForm.path"
                  label="路由地址"
                  outlined
                  :rules="[(val) => !!val || '路由地址不能为空']"
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-input
                  v-model="menuForm.component"
                  label="组件路径"
                  outlined
                  :rules="menuForm.menuType === 'C' ? [(val) => !!val || '组件路径不能为空'] : []"
                />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input v-model="menuForm.perms" label="权限标识" outlined />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-input v-model="menuForm.query" label="路由参数" outlined />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-input v-model="menuForm.icon" label="菜单图标" outlined>
                  <template v-slot:append>
                    <q-icon :name="menuForm.icon || 'help_outline'" />
                  </template>
                </q-input>
              </div>
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="menuForm.visible"
                  label="显示状态"
                  :options="visibleOptions"
                  outlined
                  emit-value
                  map-options
                />
              </div>
            </div>

            <div class="row q-col-gutter-md">
              <div class="col-md-6 col-sm-12">
                <q-select
                  v-model="menuForm.status"
                  label="状态"
                  :options="statusOptions"
                  outlined
                  emit-value
                  map-options
                />
              </div>
              <div class="col-md-6 col-sm-12">
                <q-input v-model="menuForm.remark" label="备注" outlined />
              </div>
            </div>

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 选择上级菜单对话框 -->
    <q-dialog v-model="parentDialogVisible" persistent>
      <q-card style="width: 400px">
        <q-card-section>
          <div class="text-h6">选择上级菜单</div>
        </q-card-section>
        <q-card-section>
          <q-tree
            :nodes="menuTreeForSelect"
            node-key="menuId"
            label-key="menuName"
            v-model:selected="selectedParentId"
            default-expand-all
            :no-connectors="true"
          >
            <template v-slot:default-header="prop">
              <div class="row items-center">
                <q-icon :name="prop.node.icon || 'folder'" class="q-mr-sm" />
                {{ prop.node.menuName }}
              </div>
            </template>
          </q-tree>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn label="取消" v-close-popup flat color="primary" />
          <q-btn label="确定" color="primary" @click="confirmParentSelect" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'menuName', label: '菜单名称', field: 'menuName', align: 'left' },
  {
    name: 'icon',
    label: '图标',
    field: 'icon',
    align: 'center',
    format: (val) => (val ? `<q-icon name="${val}" />` : ''),
  },
  { name: 'menuType', label: '类型', field: 'menuType', align: 'center' },
  { name: 'orderNum', label: '排序', field: 'orderNum', align: 'center' },
  { name: 'perms', label: '权限标识', field: 'perms', align: 'center' },
  { name: 'path', label: '路由地址', field: 'path', align: 'center' },
  { name: 'component', label: '组件路径', field: 'component', align: 'center' },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center' },
  { name: 'actions', label: '操作', align: 'center' },
]

// 菜单类型选项
const menuTypeOptions = [
  { label: '目录', value: 'M' },
  { label: '菜单', value: 'C' },
  { label: '按钮', value: 'F' },
]

// 菜单类型颜色
const menuTypeColors = {
  M: 'blue',
  C: 'green',
  F: 'orange',
}

// 是否外链选项
const frameOptions = [
  { label: '是', value: 1 },
  { label: '否', value: 0 },
]

// 显示状态选项
const visibleOptions = [
  { label: '显示', value: 1 },
  { label: '隐藏', value: 0 },
]

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
]

// 数据状态
const menuTree = ref([])
const flattenMenuData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const parentDialogVisible = ref(false)
const isEdit = ref(false)
const menuForm = ref(initMenuForm())
const selectedParentId = ref(null)
const currentParent = ref(null)

// 初始化菜单表单
function initMenuForm() {
  return {
    menuId: null,
    parentId: 0,
    parentName: '主类目',
    menuName: '',
    menuType: 'C',
    orderNum: 0,
    isFrame: 0,
    path: '',
    component: '',
    perms: '',
    query: '',
    icon: '',
    visible: 1,
    status: 1,
    remark: '',
  }
}

// 处理后的菜单树（用于选择上级菜单）
const menuTreeForSelect = computed(() => {
  return [
    {
      menuId: 0,
      menuName: '主类目',
      children: menuTree.value,
    },
  ]
})

// 初始化加载数据
onMounted(() => {
  loadMenuTree()
})

// 加载菜单树
function loadMenuTree() {
  loading.value = true

  // 模拟API请求
  setTimeout(() => {
    menuTree.value = [
      {
        menuId: 1,
        parentId: 0,
        menuName: '系统管理',
        menuType: 'M',
        orderNum: 1,
        path: '/system',
        component: 'Layout',
        icon: 'settings',
        status: 1,
        children: [
          {
            menuId: 11,
            parentId: 1,
            menuName: '用户管理',
            menuType: 'C',
            orderNum: 1,
            path: 'user',
            component: 'system/user/index',
            icon: 'people',
            status: 1,
          },
          {
            menuId: 12,
            parentId: 1,
            menuName: '角色管理',
            menuType: 'C',
            orderNum: 2,
            path: 'role',
            component: 'system/role/index',
            icon: 'security',
            status: 1,
          },
          {
            menuId: 13,
            parentId: 1,
            menuName: '菜单管理',
            menuType: 'C',
            orderNum: 3,
            path: 'menu',
            component: 'system/menu/index',
            icon: 'list',
            status: 1,
          },
        ],
      },
      {
        menuId: 2,
        parentId: 0,
        menuName: '系统监控',
        menuType: 'M',
        orderNum: 2,
        path: '/monitor',
        component: 'Layout',
        icon: 'monitor_heart',
        status: 1,
        children: [
          {
            menuId: 21,
            parentId: 2,
            menuName: '操作日志',
            menuType: 'C',
            orderNum: 1,
            path: 'operlog',
            component: 'monitor/operlog/index',
            icon: 'history',
            status: 1,
          },
          {
            menuId: 22,
            parentId: 2,
            menuName: '登录日志',
            menuType: 'C',
            orderNum: 2,
            path: 'logininfor',
            component: 'monitor/logininfor/index',
            icon: 'login',
            status: 1,
          },
        ],
      },
    ]

    // 扁平化菜单数据用于表格展示
    flattenMenuData.value = flattenTree(menuTree.value)
    loading.value = false
  }, 500)
}

// 扁平化树形数据
function flattenTree(tree) {
  const result = []
  const flatten = (nodes, level = 0) => {
    nodes.forEach((node) => {
      result.push({
        ...node,
        level,
        hasChildren: node.children && node.children.length > 0,
      })
      if (node.children) {
        flatten(node.children, level + 1)
      }
    })
  }
  flatten(tree)
  return result
}

// 显示新增对话框
function showAddDialog(parent) {
  isEdit.value = false
  menuForm.value = initMenuForm()

  if (parent) {
    currentParent.value = parent
    menuForm.value.parentId = parent.menuId
    menuForm.value.parentName = parent.menuName
  }

  dialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  menuForm.value = { ...row }

  // 设置父级名称
  if (row.parentId === 0) {
    menuForm.value.parentName = '主类目'
  } else {
    const parent = findParent(menuTree.value, row.menuId)
    if (parent) {
      menuForm.value.parentName = parent.menuName
    }
  }

  dialogVisible.value = true
}

// 查找父节点
function findParent(nodes, menuId) {
  for (const node of nodes) {
    if (node.children) {
      const found = node.children.find((child) => child.menuId === menuId)
      if (found) return node

      const parent = findParent(node.children, menuId)
      if (parent) return parent
    }
  }
  return null
}

// 打开选择上级菜单对话框
function openParentSelect() {
  parentDialogVisible.value = true
}

// 确认选择上级菜单
function confirmParentSelect() {
  if (selectedParentId.value === 0) {
    menuForm.value.parentId = 0
    menuForm.value.parentName = '主类目'
  } else {
    const parent = findNode(menuTree.value, selectedParentId.value)
    if (parent) {
      menuForm.value.parentId = parent.menuId
      menuForm.value.parentName = parent.menuName
    }
  }
  parentDialogVisible.value = false
}

// 查找节点
function findNode(nodes, menuId) {
  for (const node of nodes) {
    if (node.menuId === menuId) return node
    if (node.children) {
      const found = findNode(node.children, menuId)
      if (found) return found
    }
  }
  return null
}

// 清空父级选择
function clearParent() {
  menuForm.value.parentId = 0
  menuForm.value.parentName = '主类目'
}

// 提交表单
function submitForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isEdit.value ? '菜单信息已更新' : '菜单创建成功',
  })
  dialogVisible.value = false
  loadMenuTree()
}

// 切换状态
function toggleStatus(row) {
  $q.dialog({
    title: '确认',
    message: `确定要${row.status === 0 ? '启用' : '禁用'}菜单 ${row.menuName}  吗？`,
    cancel: true,
  })
    .onOk(() => {
      // 这里应该是实际的API调用
      $q.notify({
        type: 'positive',
        message: `菜单已${row.status === 0 ? '启用' : '禁用'}`,
      })
    })
    .onCancel(() => {
      // 取消操作时恢复原来的状态
      row.status = row.status === 0 ? 1 : 0
    })
}

// 确认删除
function confirmDelete(row) {
  if (row.hasChildren) {
    $q.notify({
      type: 'negative',
      message: '该菜单包含子菜单，请先删除子菜单',
    })
    return
  }

  $q.dialog({
    title: '确认删除',
    message: `确定要删除菜单 ${row.menuName}  吗？`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '菜单已删除',
    })
    loadMenuTree()
  })
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }

  // 缩进显示层级关系
  tbody tr {
    td:first-child {
      padding-left: calc(1rem * var(--level));
    }
  }
}

.q-tree {
  font-size: 16px;

  .q-tree__node-header {
    padding: 8px 0;
  }
}
</style>
